package com.logreview.consumer;

import com.logreview.ApplicationProperties;
import com.logreview.util.CoreSocketClient;
import com.logreview.util.FileUtil;
import com.logreview.util.OfepClient;
import com.logreview.util.ShellUtil;
import com.logreview.vo.FhbwVO;
import com.logreview.vo.LoggerVO;
import com.logreview.vo.Monitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BlockingQueue;

/**
 * 日志消费
 */
public class LoggerConsumer implements Runnable {
    private volatile boolean isRunning = true;
    private Logger logger = LoggerFactory.getLogger(LoggerConsumer.class);
    private BlockingQueue<LoggerVO> queue;// 内存缓冲区

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private CoreSocketClient socketClient;

    @Autowired
    private OfepClient ofepClient;

    private LoggerConsumer(){}

    public LoggerConsumer(BlockingQueue<LoggerVO> queue){
        this.queue = queue;
    }

    public void run() {
        LoggerVO vo = new LoggerVO();

        while (isRunning){
            try {
                Thread.sleep(1);
                vo = queue.take();
                logger.info("queque take success : {}",vo);
                String data = vo.getCxbw(); //历史数据系统的查询报文
                String key = "";//socketClient.apply4Key();//申请Key
                String resultHDS = "";//socketClient.sendData(key.getBytes("gbk"),data);//HDS的查询结果
                String resultOLD = "";//vo.getFhbw();//历史数据查询系统的查询结果
                FhbwVO fhbwVoHDS = getFhbwVoHDS(resultHDS);//HDS返回报文
                FhbwVO fhbwVoOLD = getFhbwVoOLD(resultOLD);//历史数据查询系统的返回报文

                //下载文件到ofep的目录
                ofepClient.download(fhbwVoHDS.getFileNmae(),fhbwVoHDS.getOfepKey());
                ofepClient.download(fhbwVoOLD.getFileNmae(),fhbwVoOLD.getOfepKey());

                String hdsFilePath = applicationProperties.getOfepLocalFilePath() + "/" + fhbwVoHDS.getFileNmae();
                String oldFilePath = applicationProperties.getOfepLocalFilePath() + "/" + fhbwVoOLD.getFileNmae();

                logger.info("ready to compare file,hdsFile:{},oldFile:{}",hdsFilePath,oldFilePath);
                //对比文件
                String shell = "diff " + hdsFilePath + " " + oldFilePath;
                String shellResult = ShellUtil.extcute(shell);


                //如果失败则记录
                if (!StringUtils.isEmpty(shellResult)){
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String line = "["+format1.format(new Date(System.currentTimeMillis()))+"],line="+ vo.getLine() + ", hdsFilePath=" + hdsFilePath+ ", oldFilePath=" + oldFilePath + ",shellResult=" + shellResult;
                               line += "\r\n";
                    String fileName = "hds.logreview." + format.format(new Date(System.currentTimeMillis())) +".failed.log";
                    String filePath = applicationProperties.getLogPath() + fileName;
                    FileUtil.append(filePath,line);
                }else{
                    //比较成功则删除文件
                    File f = new File(hdsFilePath);
                    if(f.exists()){
                        f.delete();
                    }
                    File f1 = new File(hdsFilePath);
                    if(f1.exists()){
                        f1.delete();
                    }
                }

                //消费成功记录+1
                Monitor.consumerCount.incrementAndGet();
            } catch (Exception e) {
                logger.error("Exception",e);
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //记录没有消费的数据
                String line = "["+format1.format(new Date(System.currentTimeMillis()))+"],line="+ vo.getLine();
                line += "\r\n";
                String fileName = "hds.logreview." + format.format(new Date(System.currentTimeMillis())) +".unconsumer.log";
                String filePath = applicationProperties.getLogPath() + fileName;
                try {
                    logger.info(line);
                    FileUtil.append(filePath,line);
                } catch (IOException e1) {
                    logger.error("append failed",e1);
                }
            }
        }
    }

    private FhbwVO getFhbwVoHDS(String result){
        FhbwVO fhbwVO = new FhbwVO() ;
        fhbwVO.setFileNmae("fhbwHDS.txt");
        return  fhbwVO;
    }

    private FhbwVO getFhbwVoOLD(String result){
        FhbwVO fhbwVO = new FhbwVO();
        fhbwVO.setFileNmae("fhbwOLDtxt");
        return  fhbwVO;
    }
}
